package com.ruoyi.system.wx.login;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.utils.RestTemplateUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

import static com.ruoyi.system.execute.LoadCacheManager.WX_LOGIN_CACHE;

/**
 * The type Wx login service.
 *
 * @ClassName WxLoginService
 * @Description
 * @Author sizegang
 * @Date2024/11/30 00 :06
 */
@Service
public class WxLoginService {
    private static String appId = "wx0838f6928d433171";

    private static String appSecret = "613f51c74eae3397209e4f5c12246108";

    /**
     * The Open id url.
     */
    final String OPEN_ID_URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * The Token url.
     */
    final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";

    /**
     * The Phone url.
     */
    final String PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber";


    /**
     * {
     * "session_key": "Qe3sZC4v9qeFfh58RK5QZg==",
     * "openid": "o4CKm4h6fpIeuxKVwLgddCYqLk_8",
     * "unionid": "oiE2c6YfuP67_-2IHvtIGeqEFCJU"
     * }
     */
    /**
     * Gets open id.
     *
     * @param code the code
     * @return the open id
     */
    public String getOpenId(String code, String platform) {

        Assert.notNull(platform, "platform 不能为空");

        String appId = WX_LOGIN_CACHE.get(platform + "AppId");
        String appSecret = WX_LOGIN_CACHE.get(platform + "AppSecret");
        // 请求微信 API 获取 openId
        String requestUrl = OPEN_ID_URL + "?appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";
        ResponseEntity<Map> response = RestTemplateUtil.get(requestUrl, Map.class);
        // 处理微信 API 的请求结果
        if (response.getStatusCode() == HttpStatus.OK) {
            Map<String, String> responseBody = response.getBody();
            return responseBody.get("openid");
        }
        throw new RuntimeException("Failed to obtain openId from WeChat");
    }


    /**
     * Gets access token.
     *
     * @param secondCode the second code
     * @return the access token
     */
    public String getAccessToken(String platform) {
        String appId = WX_LOGIN_CACHE.get(platform + "AppId");
        String appSecret = WX_LOGIN_CACHE.get(platform + "AppSecret");

        String requesturl = TOKEN_URL + String.format("?grant_type=client_credential&appid=%s&secret=%s", appId, appSecret);
        ResponseEntity<Map> response = RestTemplateUtil.get(requesturl, Map.class);
        if (response.getStatusCode() == HttpStatus.OK) {
            Map<String, String> responseBody = response.getBody();
            return responseBody.get("access_token");
        }
        return null;
    }

    /**
     * Gets phone number.
     *
     * @param secondCode  the second code
     * @param accessToken the access token
     * @return the phone number
     */
    public String getPhoneNumber(String secondCode, String accessToken) {
        String requesturl = PHONE_URL + String.format("?access_token=%s", accessToken);
        Map<String, Object> params = new HashMap<>();
        params.put("code", secondCode);
        ResponseEntity<Map> response = RestTemplateUtil.post(requesturl, params, Map.class);
        if (response.getStatusCode() == HttpStatus.OK) {
            Map<String, Object> responseBody = response.getBody();
            Object phoneInfo = responseBody.get("phone_info");
            if (Objects.nonNull(phoneInfo)) {
                LinkedHashMap phoneInfos = (LinkedHashMap) phoneInfo;
                Object phoneNumber = phoneInfos.get("phoneNumber");
                if (Objects.nonNull(phoneNumber)) {
                    return phoneNumber.toString();
                }
            }
        }
        return null;
    }


}
